package cn.agiledata.bank.common.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.PrivateKey;

import org.bouncycastle.util.encoders.Base64;

import ccit.security.bssp.CAUtility;
import cn.agiledata.bank.linkbank.exception.LinkBankException;

public class SignUtil {

	/**
	 * 使用证书进行签名
	 * 
	 * @return
	 */
	public static String sign(String plain) {
		
		try {
			// 读取证书
			InputStream in = SignUtil.class.getClassLoader().getResourceAsStream("cert/pay.p12");
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			byte[] p12 = bos.toByteArray();
			
			// 证书密码
			String password = "1ab3f2b5";
			
			PKCS12Util gen = new PKCS12Util();
			
			// 解析P12证书
			gen.parseP12(p12, password);
			// 获取私钥
			PrivateKey prikey = gen.getPrivateKey();
			
			byte[] inData = plain.getBytes();
			// 签名
			byte[] signData = gen.externalSign("SHA1withRSA", prikey, inData);
			System.out.println(new String(Base64.encode(signData)));
			
			return new String(Base64.encode(signData));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		return null;
	}
	
	/**
     * 根据证书验签
     * 
     * @param data
     * @param sign
     * @throws LinkBankException
     */
    public static boolean validateSign(String data, String sign,String merchantId)
            throws LinkBankException {
    	// 证书验签
    	int ret = -1;
        try {
        	System.out.println("validateSign: plain:" + data + " sing:" + sign + " merchantId:" + merchantId);
			if (sign != null && data != null) {
			    // 读取证书
			    InputStream in = Constant.class.getClassLoader().getResourceAsStream("cert/" + merchantId + ".der");
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				int buf_size = 1024;
				byte[] buffer = new byte[buf_size];
				int len = 0;
				while (-1 != (len = in.read(buffer, 0, buf_size))) {
					bos.write(buffer, 0, len);
				}
				byte[] cert = bos.toByteArray();
				ret = CAUtility.verifyWithCert(0x00000103, cert, data.getBytes(), Base64.decode(sign));
				
				System.out.println("verify sign result:" + ret);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
        
        if(ret != 0) {
            return false;
        }
        return true;
    }
}
